package com.agu.mgt.common.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.agu.common.excel.AddressReader;
import com.agu.entity.common.CmmUploadFilesEntity;
import com.agu.mgt.common.service.CmmUploadFilesService;
import com.agu.result.Result;
import com.agu.result.ResultGenerator;
import com.agu.utils.JsonUtils;

import io.swagger.annotations.ApiOperation;


@RestController
@RequestMapping("common")
public class UploadController {

	@Autowired
	private CmmUploadFilesService cmmUploadFilesService;
	
	public UploadController() {
		super();
		// TODO Auto-generated constructor stub
	}

	@RequestMapping(value = "/uploadPic", method = RequestMethod.POST)
	@ApiOperation(value = "上传图片", notes = "说明")
	@ResponseBody
	public Result uploadPic(@RequestParam("file") MultipartFile file, String id, HttpServletRequest request) {
		
		CmmUploadFilesEntity cmmUploadFiles = new CmmUploadFilesEntity();
		cmmUploadFiles.setCreateTime(new Date());
		cmmUploadFiles.setFileType(1); // 图片
		
		
		
		String webRealPath = request.getSession().getServletContext().getRealPath("./");  
		
		System.out.println(webRealPath);	
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		String filename = StringUtils.cleanPath(file.getOriginalFilename());
		
		cmmUploadFiles.setFileName(filename);
		
		String webpath =  "pictures" + File.separator + sdf.format(new Date());
		
		String filePath = webRealPath +  webpath;

		int i = filename.lastIndexOf(".");
		String ext = "";
		if(i>0)
		{
			 ext = filename.substring(i);
		}
		
	
		
		String newFileName = UUID.randomUUID().toString() + ext;

		String realPathName = filePath + File.separator + newFileName;
		
		String webPathName =  "/"+ webpath + File.separator + newFileName;

		cmmUploadFiles.setPath(realPathName);
		cmmUploadFiles.setUrl(webPathName);
		
		
		
		File dir = new File(filePath);

		if (!dir.exists()) {
			dir.mkdirs();
		}

		try {
			if (file.isEmpty()) {
				return ResultGenerator.fail("文件上传错误");
			}
			if (filename.contains("..")) {
				return ResultGenerator.fail("文件上传错误");
			}
			try (InputStream inputStream = file.getInputStream()) {
				Files.copy(inputStream, Paths.get(realPathName), StandardCopyOption.REPLACE_EXISTING);
			}
		} catch (IOException e) {
			return ResultGenerator.fail("文件上传错误");
		}

		try {
			
			cmmUploadFilesService.save(cmmUploadFiles);
			
			Map map = new HashMap();
			
			map.put("id", id);
			
			map.put("fileName", cmmUploadFiles.getFileName());
			
			map.put("fileId", cmmUploadFiles.getFileId());
			
			map.put("url", webPathName);

			return ResultGenerator.successData(map);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return ResultGenerator.fail("上传失败:" + e.getMessage());
		}
	}

	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	@ApiOperation(value = "上传文件", notes = "说明")
	@RequiresPermissions("common")
	@ResponseBody
	public Result uploadFile(@RequestParam("file") MultipartFile file, String id, HttpServletRequest request) {
		
		CmmUploadFilesEntity cmmUploadFiles = new CmmUploadFilesEntity();
		cmmUploadFiles.setCreateTime(new Date());
		cmmUploadFiles.setFileType(4); // 图片
		
		
		String webRealPath = request.getSession().getServletContext().getRealPath("./");  
		
		System.out.println(webRealPath);	
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		String filename = StringUtils.cleanPath(file.getOriginalFilename());
		cmmUploadFiles.setFileName(filename);
		
		String webpath =  "uploadFils" + File.separator + sdf.format(new Date());
		
		String filePath = webRealPath +  webpath;


		
		int i = filename.lastIndexOf(".");
		String ext = "";
		if(i>0)
		{
			 ext = filename.substring(i);
		}
		
		String newFileName = UUID.randomUUID().toString() + ext;

		String realPathName = filePath + File.separator + newFileName;
		
		String webPathName =  "/"+ webpath + File.separator + newFileName;
		
		cmmUploadFiles.setPath(realPathName);
		cmmUploadFiles.setUrl(webPathName);

		File dir = new File(filePath);

		if (!dir.exists()) {
			dir.mkdirs();
		}

		try {
			if (file.isEmpty()) {
				return ResultGenerator.fail("文件上传错误");
			}
			if (filename.contains("..")) {
				return ResultGenerator.fail("文件上传错误");
			}
			try (InputStream inputStream = file.getInputStream()) {
				Files.copy(inputStream, Paths.get(realPathName), StandardCopyOption.REPLACE_EXISTING);
			}
		} catch (IOException e) {
			return ResultGenerator.fail("文件上传错误");
		}

		try {
			
			cmmUploadFilesService.save(cmmUploadFiles);
			
			Map map = new HashMap();
			
			map.put("id", id);
			
			map.put("url", webPathName);
			
			map.put("fileName", cmmUploadFiles.getFileName());
			
			map.put("fileId", cmmUploadFiles.getFileId());

			return ResultGenerator.successData(map);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return ResultGenerator.fail("上传失败:" + e.getMessage());
		}

	}
	
	@RequestMapping(value = "/uploadAddress", method = RequestMethod.POST)
	@ApiOperation(value = "上传文件", notes = "说明")
	@RequiresPermissions("common")
	@ResponseBody
	public Result uploadAddress(@RequestParam("file") MultipartFile file, String id, HttpServletRequest request) {
		
		CmmUploadFilesEntity cmmUploadFiles = new CmmUploadFilesEntity();
		cmmUploadFiles.setCreateTime(new Date());
		cmmUploadFiles.setFileType(3); // 图片
		
		String webRealPath = request.getSession().getServletContext().getRealPath("./");  
		
		System.out.println(webRealPath);	
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		String filename = StringUtils.cleanPath(file.getOriginalFilename());
		cmmUploadFiles.setFileName(filename);
		
		String webpath =  "uploadFils" + File.separator + sdf.format(new Date());
		
		String filePath = webRealPath +  webpath;

		int i = filename.lastIndexOf(".");
		String ext = "";
		if(i>0)
		{
			 ext = filename.substring(i);
		}
		
		String newFileName = UUID.randomUUID().toString() + ext;

		String realPathName = filePath + File.separator + newFileName;
		
		String webPathName =  "/"+ webpath + File.separator + newFileName;
		
		cmmUploadFiles.setPath(realPathName);
		cmmUploadFiles.setUrl(webPathName);
		
		File dir = new File(filePath);

		if (!dir.exists()) {
			dir.mkdirs();
		}

		try {
			if (file.isEmpty()) {
				return ResultGenerator.fail("文件上传错误");
			}
			if (filename.contains("..")) {
				return ResultGenerator.fail("文件上传错误");
			}
			try (InputStream inputStream = file.getInputStream()) {
				Files.copy(inputStream, Paths.get(realPathName), StandardCopyOption.REPLACE_EXISTING);
			}
		} catch (IOException e) {
			return ResultGenerator.fail("文件上传错误");
		}

		try {
			
			Set mobiles = AddressReader.readerMobils(realPathName);
			
			String mobileList = JsonUtils.toJson(mobiles);
			
			cmmUploadFiles.setMobileList(mobileList);
			
			cmmUploadFilesService.save(cmmUploadFiles);
			
			Map map = new HashMap();
			
			map.put("id", id);
			
			map.put("url", webPathName);
			
			map.put("fileName", cmmUploadFiles.getFileName());
			
			map.put("fileId", cmmUploadFiles.getFileId());
			
			map.put("mobileNum", mobiles.size());
			

			return ResultGenerator.successData(map);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return ResultGenerator.fail("上传失败:" + e.getMessage());
		}

	}

}
